// 监听键盘事件
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'registerHotkey') {
    // 仅在当前激活的标签页监听键盘事件
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs.length > 0) {
        chrome.tabs.sendMessage(tabs[0].id, { action: 'startListening' });
      }
    });
  } else if (request.action === 'getEnabledStatus') {
    // 获取快捷键启用状态
    chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
      sendResponse({ enabled: result.hotkeyEnabled !== false });
    });
    return true; // 保持消息通道开启直到异步操作完成
  } else if (request.action === 'setEnabledStatus') {
    // 设置快捷键启用状态
    chrome.storage.sync.set({ hotkeyEnabled: request.enabled }, () => {
      // 通知所有标签页更新状态
      chrome.tabs.query({}, (tabs) => {
        tabs.forEach(tab => {
          chrome.tabs.sendMessage(tab.id, { 
            action: request.enabled ? 'startListening' : 'stopListening' 
          });
        });
      });
      sendResponse({ success: true });
    });
    return true;
  }
});

// 当标签页更新时重新注册快捷键
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    // 检查快捷键是否启用
    chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
      if (result.hotkeyEnabled !== false) {
        chrome.tabs.sendMessage(tabId, { action: 'startListening' });
      }
    });
  }
});

// 当标签页激活时重新注册快捷键
chrome.tabs.onActivated.addListener((activeInfo) => {
  // 检查快捷键是否启用
  chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
    if (result.hotkeyEnabled !== false) {
      chrome.tabs.sendMessage(activeInfo.tabId, { action: 'startListening' });
    }
  });
});

// 初始化存储
chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
    if (result.hotkeyEnabled === undefined) {
      chrome.storage.sync.set({ hotkeyEnabled: true });
    }
  });
});
